#include <iostream>
#include <cassert>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#define MAX 1024
int main()
{
    //1.建立管道
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    assert(n == 0);
    (void)n;
     std::cout << "pipefd[0]: " << pipefd[0] << ", pipefd[1]: " << pipefd[1] << std::endl;
    //2.创建子进程
    pid_t id = fork();
    //3.子写父读
    if(id == 0)
    {
        //child
        // 第3步，父子关闭不需要的fd，形成单向通信的管道
        //孩子关闭读
        close(pipefd[0]);
        int cnt = 0;
        while(true)
        {
            char message[MAX];
            snprintf(message,sizeof(message),"I am child mypid: %d , myppid: %d ,cnt: %d",getpid(),getppid(),cnt++);
            write(pipefd[1],message,strlen(message));
            sleep(1);
        }

    }
    else
    {
        //父亲关闭写
        close(pipefd[1]);

        //father
        char buffer[MAX];
        while(true)
        {
            ssize_t n = read(pipefd[0],buffer,sizeof(buffer) - 1);
            if(n > 0)
            {
                buffer[n] = 0;
                std::cout << getpid() << ", " << "child say: " << buffer << " to me!" << std::endl;
            }
            std::cout << "father return val(n): " << n << std::endl;
            sleep(1);
        }

    }

    close(pipefd[0]);
    return 0;
}